using System;
using System.Xml;

namespace ELS.Configuration
{
	/// <summary>
	/// A factory that encapsulates the knowledge of which <see cref="ELS.Configuration.ConfigurationProvider "/> to create.
	/// </summary>
	public sealed class ConfigurationProviderFactory
	{
		/// <summary>
		/// the constructor is marked private to disable class instantiation
		/// </summary>
		private ConfigurationProviderFactory()
		{
		}

		/// <summary>
		/// Creates and returns a <see cref="ELS.Configuration.ConfigurationProvider "/> of the specified type.
		/// </summary>
		/// <param name="providerSettingsXml">an xml string containing the settings for the provider to create.</param>
		/// <returns>An instance of a <see cref="ELS.Configuration.ConfigurationProvider "/>.</returns>
		public static ConfigurationProvider Create( string providerSettingsXml )
		{
			if ( providerSettingsXml != null)
			{
				XmlDocument doc = new XmlDocument();
				doc.LoadXml( providerSettingsXml );

				XmlNamespaceManager nsmgr = new XmlNamespaceManager( doc.NameTable );
				nsmgr.AddNamespace( Constants.NAMESPACE_PREFIX, Constants.NAMESPACE_URI );

				return Create ( doc.DocumentElement );
			}
			throw new ApplicationException( "Unable to create a configuration provider" );
		}

		/// <summary>
		/// Creates and returns a <see cref="ELS.Configuration.ConfigurationProvider "/> of the specified type.
		/// </summary>
		/// <param name="providerNode">an xml node containing the settings for the provider to create.</param>
		/// <returns>An instance of a <see cref="ELS.Configuration.ConfigurationProvider "/>.</returns>
		internal static ConfigurationProvider Create( XmlNode providerNode )
		{
			if ( providerNode == null )
				throw new ApplicationException( "Missing provider settings."); 

			string providerType = ( providerNode.Attributes["type"] != null ) ? providerNode.Attributes["type"].InnerText: null;
			string path = ( providerNode.Attributes["path"] != null ) ? providerNode.Attributes["path"].InnerText : null;

			switch ( providerType.ToUpper())
			{
				default:
				case "LOCALFILE" :
					return new LocalFileConfigurationProvider( path );
			}
		}

	}
}
